//
//  XS_AccountSafeVC.swift
//  XueDao
//
//  Created by Mac on 2020/12/12.
//

import UIKit

class XS_AccountSafeVC: XS_BaseVC {
    
    var model : XS_UserBOM?

    @IBOutlet weak var tableView: UITableView!
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        view.backgroundColor = #colorLiteral(red: 0.968627451, green: 0.968627451, blue: 0.968627451, alpha: 1)
        title = "账号与安全"
        tableView.contentInset = UIEdgeInsets.init(top: 0, left: 0, bottom: .bottomHeight, right: 0)
        tableView.register(UINib.init(nibName: "XS_SetListCell", bundle: Bundle.main), forCellReuseIdentifier: "XS_SetListCell")
        tableView.register(UINib.init(nibName: "XS_WeChatBindCell", bundle: Bundle.main), forCellReuseIdentifier: "XS_WeChatBindCell")
        tableView.delegate = self
        tableView.dataSource = self
        
        tableView.backgroundColor = UIColor(red: 0.97, green: 0.97, blue: 0.97, alpha: 1.0)
    }


    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}

extension XS_AccountSafeVC : UITableViewDelegate,UITableViewDataSource{
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "XS_SetListCell", for: indexPath) as! XS_SetListCell
            cell.nextImageView.isHidden = false
            cell.titleLabel.text = "已绑定手机"
            if model != nil {
                cell.rightNextLabel.text = model?.phone ?? ""
            }
            cell.rightLabel.text = ""
            cell.cellarSwitch.isHidden = true
            cell.rightImageView.image = UIImage.init()
            return cell
        }
        let cell = tableView.dequeueReusableCell(withIdentifier: "XS_WeChatBindCell", for: indexPath) as! XS_WeChatBindCell
        cell.delegate = self
        cell.reloadData()
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 50
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 0 {
            return 0
        }
        return 45
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView.init(frame: CGRect.init(x: 0, y: 0, width: .screenWidth, height: 8))
        view.backgroundColor = UIColor.qmui_color(withHexString: "#F7F7F7")
        let label = UILabel.init(frame: CGRect.init(x: 12, y: 16, width: 200, height: 21))
        label.text = "社交账号绑定"
        label.textColor = UIColor.qmui_color(withHexString: "#AAB1B7")
        label.font = .systemFont(ofSize: 15)
        view.addSubview(label)
        return view
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.section == 0 {
            let bindVC = XS_BindMobileVC()
            bindVC.model = model
            navigationController?.pushViewController(bindVC, animated: true)
        }else{
            if XS_Singleton.shared.infoModel?.userBO.wechat.count ?? 0 > 0 {
                return
            }
            let req = SendAuthReq()
            req.scope = "snsapi_userinfo"
            req.state = "App"
            WXApi.sendAuthReq(req, viewController: self, delegate: nil)
            NotificationCenter.default.rx
                .notification(Notification.Name("XS_WeixinM"))
                .subscribe(onNext: { [weak self] noti in
                    guard let `self` = self, let object = noti.object as? XS_WeixinM else { return }
                    print(object.openid)
                    XS_Singleton.shared.infoModel?.userBO.openId = object.openid
                    let infoModel = XS_MineInfoModel.deserialize(from: XS_Singleton.shared.infoModel?.userBO.toJSON())
                    XS_NetWork.requestJson("/user/updateUser", parameters: infoModel?.toJSON())
                        .subscribe(onNext: { resp in
                            if resp.success{
                                self.tableView.reloadData()
                            }else{
                                self.view.makeToast(resp.msg)
                            }
                        }).disposed(by: self.disposeBag)
                }).disposed(by: disposeBag)
        }
    }
}

extension XS_AccountSafeVC : XS_WeChatBindCellDelegate{
    func bindCell(bindCell: XS_WeChatBindCell, didClickUnbindBtn: UIButton) {
        
        XS_NetWork.requestJson("/user/untie")
            .filter({$0.success})
            .subscribe(onNext: { resp in
                XS_Singleton.shared.infoModel?.userBO.openId = ""
                self.tableView.reloadData()
            }).disposed(by: disposeBag)
    }
    
    
}

